from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from rest_framework.views import APIView
from headlines.models import Channel, Article
from rest_framework.decorators import action
from questions.models import Label
from rest_framework.response import Response
from headlines.serializers import ChannelListModerSerializer, \
    ArticleModelsSerializer, ArticleSerialzier, LabelMobelSerializer, \
    ArticleSerializerForDetail, ArticleSerializerForList, \
    CommentSerializerForCreate, SearchArticleSerializer

from headlines.utils import PageNum
from django.conf import settings


# 获取图片路径

class PublicImgView(APIView):

    def post(self, request):
        data = request.FILES.get('img')
        print(data)

        from fdfs_client.client import Fdfs_client
        # 创建对象
        client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        print(settings.FDFS_CLIENT_CONF)
        # 上传图片
        result = client.upload_by_buffer(data.read())

        # 判断是否上传成功
        if result['Status'] != 'Upload successed.':
            return Response(status=401)

        # 获取上传后的路径
        image_url = result['Remote file_id']

        print(image_url)
        imag_url = settings.FDFS_URL + image_url

        return Response({'imgurl': imag_url})


class ChannelModelViewSet(ModelViewSet):
    queryset = Channel.objects.all()

    serializer_class = ChannelListModerSerializer

    pagination_class = PageNum


class ArticleModelViewSet(ModelViewSet):
    queryset = Article.objects.all()

    lookup_field = 'id'

    # serializer_class = ArticleModelsSerializer

    pagination_class = PageNum

    # def get_queryset(self):
    #     # 获取前端传递的keyword值
    #     # keyword = self.request.query_params.get('keyword')
    #     keyword = self.kwargs.get('id')
    #
    #     # 如果keyword是空字符，则说明要获取所有用户数据
    #     if keyword is '' or keyword is None:
    #         return Article.objects.all()
    #     else:
    #         return Article.objects.filter(id=keyword)

    #  发布文章
    def create(self, request, *args, **kwargs):

        labels = self.request.data.get('labels')
        content = self.request.data.get('content')
        title = self.request.data.get('title')
        channel = self.request.data.get('channel')
        image = self.request.data.get('image')

        article = Article(title=title,
                          content=content,
                          channel_id=channel,
                          user_id=request.user.id,
                          image=image)
        article.save()

        for value in labels:

            try:

                label = Label.objects.get(id=value)

                article.labels.add(label)

                article.save()
            except:
                return Response({'success': False,
                                 'message': '创建失败'})

        return Response({'success': True,
                         'artcleid': article.id,
                         'message': '创建成功'})

    # 按频道获取文章列表 /article/{id}/channel/
    @action(methods=['get'], detail=True)
    def channel(self, request, id=None):

        if id == "-1":
            articles = self.get_queryset()
        else:
            channel = Channel.objects.get(id=int(id))
            articles = self.get_queryset().filter(channel=channel)

        page = self.paginate_queryset(articles)
        if page is not None:
            s = ArticleSerializerForList(page, many=True)
            return self.get_paginated_response(s.data)
        else:
            s = ArticleSerializerForList(instance=articles, many=True)
            return Response(s.data)

    # 收藏
    @action(methods=['put'], detail=True)
    def collect(self, request, id=None):

        article = self.get_object()
        user = request.user

        if user is not None and user.is_authenticated:

            if user not in article.collected_users.all():

                article.collected_users.add(user)
                article.save()
                return Response({'success': True,
                                 'message': '收藏成功'})
            else:
                article.collected_users.remove(request.user)
                article.save()

                return Response({'success': True,
                                 'message': '取消收藏成功'})
        else:

            return Response({'success': False,
                             'message': '未登录'},
                            status=400)

    # 文章详情  /article/{id}/
    def retrieve(self, request, *args, **kwargs):
        article = super().get_object()
        if article.visits is not None:
            article.visits += 1  # 浏览量
            article.save()  # 保存
        else:
            article.visits = 1  # 浏览量
            article.save()  # 保存
        s = ArticleSerializerForDetail(instance=article)  # 用序列化器生成所有字段和数据

        return Response(s.data)

    # 文章列表
    def list(self, request, *args, **kwargs):
        articles = super().get_queryset()
        s = ArticleSerializerForList(instance=articles, many=True)
        return Response(s.data)

    @action(methods=['post'], detail=True)
    def publish_comment(self, request, id):
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            article = self.get_object()
            article.comment_count += 1  # 点评数加一
            article.save()
            request_params = request.data
            request_params['user'] = user.id
            request_params['article'] = article.id
            s = CommentSerializerForCreate(data=request_params)
            s.is_valid(raise_exception=True)
            s.save()
            return Response({'success': True, 'message': '评论成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


class LabelAPIView(APIView):

    def get(self, request):
        label = Label.objects.all()

        serializer = LabelMobelSerializer(label, many=True)

        return Response(serializer.data)


# ========================搜索文章=========================
class SearchAtticleGenericViewSet(ModelViewSet):
    pagination_class = PageNum
    queryset = Article.objects.all()
    serializer_class = SearchArticleSerializer

    def get_queryset(self):
        data = self.request.query_params.get('text')
        if data:
            try:
                search_result = Article.objects.filter(title__contains=data)
                if not search_result:
                    try:

                        search_result = Article.objects.filter(content__contains=data)

                    except Article.DoesNotExist:

                        return Response({'success': False,
                                         'message': '未找到'},
                                        status=404)
            except Article.DoesNotExist:

                search_result = Article.objects.all()

        else:

            search_result = Article.objects.all()

        return search_result

# ========================搜索文章=========================
